"use client";
import React, { useEffect, useState, useCallback } from "react";
import {
  Button,
  Col,
  Form,
  Input,
  Row,
  Table,
  Modal,
  Select,
  Card,
  Space,
  Popconfirm,
  Tabs,
  App,
  DatePicker,
  Statistic,
} from "antd";
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  NotificationOutlined,
  MailOutlined,
  SendOutlined,
  EditOutlined,
  DeleteOutlined,
} from "@ant-design/icons";
import { system } from "@/forent-api/api";
import moment from "moment";
import { renderTargetSelector, tableColumns } from "./tools";

const { TextArea } = Input;
const { TabPane } = Tabs;
const { Option } = Select;

// 通知类型选项
const noticeTypeOptions = [
  { label: "普通通知", value: "info", color: "blue" },
  { label: "警告通知", value: "warning", color: "orange" },
  { label: "错误通知", value: "error", color: "red" },
  { label: "成功通知", value: "success", color: "green" },
];

// 优先级选项
const priorityOptions = [
  { label: "普通", value: 0, color: "default" },
  { label: "重要", value: 1, color: "orange" },
  { label: "紧急", value: 2, color: "red" },
];

// 发送类型选项
const sendTypeOptions = [
  { label: "手动发送", value: "manual" },
  { label: "定时发送", value: "scheduled" },
  { label: "系统事件", value: "system" },
];

// 目标类型选项
const targetTypeOptions = [
  { label: "指定用户", value: "user" },
  { label: "指定角色", value: "role" },
  { label: "指定部门", value: "dept" },
  { label: "全部用户", value: "all" },
];

// 状态选项
const statusOptions = [
  { label: "草稿", value: 0, color: "default" },
  { label: "已发送", value: 1, color: "green" },
  { label: "发送中", value: 2, color: "blue" },
  { label: "发送失败", value: 3, color: "red" },
];

const SystemNoticeContent: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [submitLoading, setSubmitLoading] = useState(false);
  const [tableData, setTableData] = useState<any[]>([]);
  const [total, setTotal] = useState(0);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchForm] = Form.useForm();
  const [modalVisible, setModalVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState<any>(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<any[]>([]);
  const [stats, setStats] = useState<any>({});
  const [users, setUsers] = useState<any[]>([]);
  const [depts, setDepts] = useState<any[]>([]);
  const [roles, setRoles] = useState<any[]>([]);
  const { message, modal } = App.useApp();

  // 获取通知列表
  const fetchData = useCallback(
    async (params = {}) => {
      setLoading(true);
      try {
        const searchValues = searchForm.getFieldsValue();
        const response = await system.getNoticeList({
          current,
          pageSize,
          ...searchValues,
          ...params,
        });
        if (response.code === 200) {
          setTableData(response.data.list || []);
          setTotal(response.data.total || 0);
          setCurrent(response.data.current || current);
        }
      } catch (error) {
        console.log("获取通知列表失败:", error);
      } finally {
        setLoading(false);
      }
    },
    [current, pageSize, searchForm]
  );

  // 获取统计信息
  const fetchStats = useCallback(async () => {
    try {
      const response = await system.getNoticeStats();
      if (response.code === 200) {
        setStats(response.data);
      }
    } catch (error) {
      console.log("获取统计信息失败:", error);
    }
  }, []);

  // 获取用户列表
  const fetchUsers = useCallback(async () => {
    try {
      const response = await system.getUserList({ page: 1, pageSize: 1000 });
      if (response.code === 200) {
        setUsers(response.data.list || []);
      }
    } catch (error) {
      console.log("获取用户列表失败:", error);
    }
  }, []);

  // 获取部门列表
  const fetchDepts = useCallback(async () => {
    try {
      const response = await system.getDeptList({});
      if (response.code === 200) {
        setDepts(response.data || []);
      }
    } catch (error) {
      console.log("获取部门列表失败:", error);
    }
  }, []);

  // 获取角色列表
  const fetchRoles = useCallback(async () => {
    try {
      const response = await system.getRoleList({ page: 1, pageSize: 1000 });
      if (response.code === 200) {
        setRoles(response.data.list || []);
      }
    } catch (error) {
      console.log("获取角色列表失败:", error);
    }
  }, []);

  useEffect(() => {
    fetchData();
    fetchStats();
    fetchUsers();
    fetchDepts();
    fetchRoles();
  }, [fetchData, fetchStats, fetchUsers, fetchDepts, fetchRoles]);

  // 搜索
  const handleSearch = () => {
    setCurrent(1);
    fetchData();
  };

  // 重置
  const handleReset = () => {
    searchForm.resetFields();
    setCurrent(1);
    fetchData();
  };

  // 新增
  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    form.setFieldsValue({
      notice_type: "info",
      priority: 0,
      send_type: "manual",
      target_type: "user",
    });
    setModalVisible(true);
  };

  // 编辑
  const handleEdit = (record: any) => {
    setEditingRecord(record);
    form.setFieldsValue({
      ...record,
      target_ids: record.target_ids ? JSON.parse(record.target_ids) : undefined,
      send_config: record.send_config
        ? JSON.parse(record.send_config)
        : undefined,
      send_time: record.send_time ? moment(record.send_time) : undefined,
    });
    setModalVisible(true);
  };

  // 保存
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      setSubmitLoading(true);

      const submitData = {
        ...values,
        send_time: values.send_time
          ? values.send_time.format("YYYY-MM-DD HH:mm:ss")
          : null,
        target_ids: values.target_ids || [],
        send_config: values.send_config || {},
        // 确保必填字段不为空
        title: values.title?.trim() || "",
        content: values.content?.trim() || "",
        notice_type: values.notice_type || "info",
        priority: values.priority !== undefined ? values.priority : 0,
        send_type: values.send_type || "manual",
        target_type: values.target_type || "user",
      };

      // 清理空值和无效数据
      Object.keys(submitData).forEach((key) => {
        if (submitData[key] === undefined) {
          delete submitData[key];
        }
      });

      let response;
      if (editingRecord) {
        submitData.id = editingRecord.id;
        response = await system.updateNotice(submitData);
      } else {
        response = await system.addNotice(submitData);
      }

      if (response.code === 200) {
        message.success(editingRecord ? "更新成功" : "新增成功");
        setModalVisible(false);
        fetchData();
        fetchStats();
      } else {
        message.error(response.msg || "操作失败");
      }
    } catch (error) {
      console.log("保存失败:", error);
      message.error("保存失败，请检查输入数据");
    } finally {
      setSubmitLoading(false);
    }
  };

  // 删除
  const handleDelete = async (ids: any[]) => {
    try {
      setLoading(true);
      const response = await system.deleteNotice({ ids });

      if (response.code === 200) {
        message.success("删除成功");
        setSelectedRowKeys([]);
        fetchData();
        fetchStats();
      } 
    } catch (error) {
      console.log("删除失败:", error);
    } finally {
      setLoading(false);
    }
  };

  // 发送通知
  const handleSend = async (record: any) => {
    setLoading(true);
    try {
      const response = await system.sendNotice({ id: record.id });
      if (response.code === 200) {
        message.success("发送成功");
        fetchData();
      } 
    } catch (error) {
      console.log("发送失败:", error);
      message.error("发送失败");
    } finally {
      setLoading(false);
    }
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: any[]) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
  };

  return (
    <div className="h-full flex flex-col">
      {/* 统计卡片 */}
      <Row gutter={8} className="mb-2">
        <Col span={6}>
          <Card>
            <Statistic
              title="总通知数"
              value={stats.totalCount || 0}
              prefix={<NotificationOutlined />}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="已发送"
              value={stats.sentCount || 0}
              prefix={<SendOutlined />}
              valueStyle={{ color: "#3f8600" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="草稿"
              value={stats.draftCount || 0}
              prefix={<EditOutlined />}
              valueStyle={{ color: "#cf1322" }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic
              title="今日发送"
              value={stats.todaySentCount || 0}
              prefix={<MailOutlined />}
              valueStyle={{ color: "#1890ff" }}
            />
          </Card>
        </Col>
      </Row>

      {/* 搜索表单 */}
      <Card className="mb-2">
        <div className="flex items-center justify-between">
          <Form form={searchForm} layout="inline" className="flex-1">
            <Form.Item name="title" label="标题">
              <Input placeholder="请输入标题" />
            </Form.Item>
            <Form.Item name="notice_type" label="类型">
              <Select placeholder="选择类型" allowClear style={{ width: 120 }}>
                {noticeTypeOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item name="status" label="状态">
              <Select placeholder="选择状态" allowClear style={{ width: 120 }}>
                {statusOptions.map((opt) => (
                  <Option key={opt.value} value={opt.value}>
                    {opt.label}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  icon={<SearchOutlined />}
                  onClick={handleSearch}
                >
                  搜索
                </Button>
                <Button icon={<ReloadOutlined />} onClick={handleReset}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <div className="flex items-center gap-2">
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增通知
            </Button>
            {selectedRowKeys.length > 0 && (
              <Popconfirm
                title={`确定删除选中的 ${selectedRowKeys.length} 条记录吗？`}
                onConfirm={() => handleDelete(selectedRowKeys)}
              >
                <Button danger icon={<DeleteOutlined />}>
                  批量删除
                </Button>
              </Popconfirm>
            )}
            <Button icon={<ReloadOutlined />} onClick={() => fetchData()}>
              刷新
            </Button>
          </div>
        </div>
      </Card>

      {/* 表格 */}
      <Card className="flex-1">
        <Table
          rowKey="id"
          columns={tableColumns(
            handleEdit,
            handleSend,
            handleDelete,
            noticeTypeOptions,
            priorityOptions,
            statusOptions
          )}
          dataSource={tableData}
          rowSelection={rowSelection}
          loading={loading}
          scroll={{ y: "calc(100vh - 366px)" }}
          size="small"
          pagination={{
            position: ["bottomCenter"],
            current,
            pageSize,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, size) => {
              setCurrent(page);
              setPageSize(size || 10);
            },
          }}
        />
      </Card>

      {/* 新增/编辑弹窗 */}
      <Modal
        title={editingRecord ? "编辑通知" : "新增通知"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setModalVisible(false)}>
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            loading={submitLoading}
            onClick={handleSave}
          >
            保存
          </Button>,
        ]}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{
            notice_type: "info",
            priority: 0,
            send_type: "manual",
            target_type: "user",
          }}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="title"
                label="通知标题"
                rules={[{ required: true, message: "请输入通知标题" }]}
              >
                <Input placeholder="请输入通知标题" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="notice_type"
                label="通知类型"
                rules={[{ required: true, message: "请选择通知类型" }]}
              >
                <Select>
                  {noticeTypeOptions.map((opt) => (
                    <Option key={opt.value} value={opt.value}>
                      {opt.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="content"
            label="通知内容"
            rules={[{ required: true, message: "请输入通知内容" }]}
          >
            <TextArea rows={4} placeholder="请输入通知内容" />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="priority" label="优先级">
                <Select>
                  {priorityOptions.map((opt) => (
                    <Option key={opt.value} value={opt.value}>
                      {opt.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="send_type" label="发送方式">
                <Select>
                  {sendTypeOptions.map((opt) => (
                    <Option key={opt.value} value={opt.value}>
                      {opt.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            noStyle
            shouldUpdate={(prev, curr) => prev.send_type !== curr.send_type}
          >
            {({ getFieldValue }) => {
              const sendType = getFieldValue("send_type");
              return sendType === "scheduled" ? (
                <Form.Item
                  name="send_time"
                  label="定时发送时间"
                  rules={[{ required: true, message: "请选择发送时间" }]}
                >
                  <DatePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    style={{ width: "100%" }}
                  />
                </Form.Item>
              ) : null;
            }}
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="target_type"
                label="发送目标"
                rules={[{ required: true, message: "请选择发送目标" }]}
              >
                <Select>
                  {targetTypeOptions.map((opt) => (
                    <Option key={opt.value} value={opt.value}>
                      {opt.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                noStyle
                shouldUpdate={(prev, curr) =>
                  prev.target_type !== curr.target_type
                }
              >
                {({ getFieldValue }) => {
                  const targetType = getFieldValue("target_type");
                  return targetType && targetType !== "all" ? (
                    <Form.Item
                      name="target_ids"
                      label="选择目标"
                      rules={[{ required: true, message: "请选择发送目标" }]}
                    >
                      {renderTargetSelector(targetType, users, roles, depts)}
                    </Form.Item>
                  ) : null;
                }}
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

// 系统通知主组件
export default function SystemNotice() {
  return (
    <div className="h-full rounded-[10px] px-2">
      <SystemNoticeContent />
    </div>
  );
}
